package top.go2do.common.httpResponseResult;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Arrays;
import java.util.List;

/**
 * @author xingyuji
 * @date 2025/3/9 17:43
 * @description
 */
@Slf4j
@RestControllerAdvice
public class GlobalResponseWrapper implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // 排除已提交的响应和ApiResponse类型
        if (isResponseCommitted()) {
            return false;
        }

        // 获取当前请求的 HttpServletRequest 对象
        // 通过RequestContextHolder获取当前请求的属性
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();
        String requestUri = request.getRequestURI();
        log.info("GlobalResponseWrapper requestUri:{}", requestUri);
        // 排除不需要包装的路径：Spring Doc 的端点
        // 根据你的实际路径调整，常见的包括：
        List<String> excludePaths = Arrays.asList(
                "/v3/api-docs",
                "/swagger-ui",
                "/doc.html",
                "/webjars",
                "/swagger-resources"
        );

        for (String path : excludePaths) {
            // 正则匹配
            if (requestUri.startsWith(path)) {
                return false;
            }
        }

        Class<?> returnClass = returnType.getParameterType();
        return !ApiResponse.class.isAssignableFrom(returnClass)
                || returnClass == void.class;
    }

    private boolean isResponseCommitted() {
        RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
        if (attrs instanceof ServletRequestAttributes) {
            HttpServletResponse response = ((ServletRequestAttributes) attrs).getResponse();
            return response != null && response.isCommitted();
        }
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType mediaType, Class selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {

        // 处理void返回类型
        if (body == null && returnType.getParameterType() == void.class) {
            return ApiResponse.success(null);
        }

        // 重点：String类型返回值不处理
        if (returnType.getParameterType().equals(String.class)) {
            return body;
        }

        // 正常返回结果包装
        ApiResponse<?> apiResponse = (body instanceof ApiResponse)
                ? (ApiResponse<?>) body
                : ApiResponse.success(body);
        return apiResponse;
    }
}
